package com.rfid.assistant.activity.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.preference.EditTextPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceFragmentCompat;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonWriter;
import com.rfid.assistant.BluetoothManager;
import com.rfid.assistant.R;
import com.rfid.event.SendStatus;
import com.rfid.sockethelper.ClientManager;
import com.rfid.sockethelper.ClientSocketHelper;
import com.rfid.sockethelper.IOHelper;
import com.rfid.sockethelper.SocketBase;
import com.rfid.socketio.SocketIoInstance;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class SafeDoorConfigFragment extends PreferenceFragmentCompat implements SocketBase.OnReceiveListener{

    private PreferenceCategory mRoot;
    private String mIp;
    private String mName;
    private boolean isBluetooth;
    private boolean isRemote;
    private List<String> mFiles;
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.config_file_preference, rootKey);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        System.out.println("onAttach");
        ClientManager.getManager().addListener(this);
        BluetoothManager.INSTANCE.addListener(this);
        SocketIoInstance.INSTANCE.setOnReceiveListener(this);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        System.out.println("onDetach");
        ClientManager.getManager().removeListener(this);
        BluetoothManager.INSTANCE.removeListener(this);
        SocketIoInstance.INSTANCE.setOnReceiveListener(null);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mIp = getActivity().getIntent().getStringExtra("ip");
        isRemote = getActivity().getIntent().getBooleanExtra("remote",false);
        isBluetooth = getActivity().getIntent().getBooleanExtra("bluetooth",false);
        mRoot = findPreference("header");
        if (isBluetooth) {
            BluetoothManager.INSTANCE.sendConfigsReq(mIp);
        } else if (isRemote) {
            SocketIoInstance.INSTANCE.getClient().sendConfigsReq();
        } else {
            ClientSocketHelper client = ClientManager.getManager().getClient(mIp);
            if (client != null) {
                client.sendConfigsReq();
            }
        }
    }

    public boolean handleBackPress() {
        if (mName == null) {
            return false;
        }
        mName = null;
        mRoot.setTitle("选择文件");
        addFilesPreferences(mFiles);
        return true;
    }

    private void addConfigPreference(String text) {
        mRoot.removeAll();
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(text).getAsJsonObject();
        for (String key:jsonObject.keySet()) {
            JsonElement element = jsonObject.get(key);
            String value = null;
            if (element.isJsonArray()) {
                value = element.getAsJsonArray().toString();
            } else if (element.isJsonObject()){
                value = element.getAsJsonObject().toString();
            } else if (element.isJsonNull()) {

            } else {
                value = element.getAsString();
            }
            EditTextPreference preference = new EditTextPreference(getContext());
            preference.setTitle(key);
            preference.setKey(key);
            preference.setText(value);
            preference.setPersistent(false);
            preference.setIconSpaceReserved(false);
            preference.setSummaryProvider(EditTextPreference.SimpleSummaryProvider.getInstance());
            mRoot.addPreference(preference);
        }
    }

    private void addFilesPreferences(List<String> files) {
        mRoot.removeAll();
        for (String name:files) {
            Preference preference = new Preference(getContext());
            preference.setTitle(name);
            preference.setIconSpaceReserved(false);
            preference.setKey(name);
            mRoot.addPreference(preference);
        }
    }

    @Override
    public boolean onPreferenceTreeClick(Preference preference) {
        System.out.println(preference.getKey());
        if (preference instanceof EditTextPreference) {
        } else {
            if (isBluetooth) {
                BluetoothManager.INSTANCE.sendConfigReq(mIp,preference.getKey());
            } else if (isRemote) {
                SocketIoInstance.INSTANCE.getClient().sendConfigReq(preference.getKey());
            }
            else {
                ClientSocketHelper clientSocketHelper = ClientManager.getManager().getClient(mIp);
                if (clientSocketHelper != null) {
                    clientSocketHelper.sendConfigReq(preference.getKey());
                }
            }
        }
        return super.onPreferenceTreeClick(preference);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onReceived(String ip, short cmd, CharSequence... text) {
        if (cmd == IOHelper.CMD_RESPON_CONFIGS) {
            Gson gson = new Gson();
            Type type = new TypeToken<ArrayList<String>>(){}.getType();
            List<String> files = gson.fromJson(text[0].toString(),type);
            mFiles = files;
            addFilesPreferences(files);
        } else if (cmd == IOHelper.CMD_SET_CONFIG) {
            mName = text[0].toString();
            mRoot.setTitle(text[0]);
            System.out.println(text);
            addConfigPreference(text[1].toString());
        }
    }

    @Override
    public void onConnect(String ip, boolean connect) {
        if (mIp.equals(ip) && !connect) {
            System.out.println("connect reset!");
        }
        if (!connect) {
            Toast.makeText(getActivity(),"连接已断开",Toast.LENGTH_LONG).show();
        }
    }

//    @Override
//    public void onConfig(String ip, String name, String text) {
//        mRoot.setTitle(name);
//        mName = name;
//        System.out.println(text);
//        addConfigPreference(text);
//    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.config,menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        System.out.println("onOptionsItemSelected id = " + id);
        if (id == R.id.save) {
            int count = mRoot.getPreferenceCount();
            JsonObject jsonObject = new JsonObject();
            for (int i=0;i<count;i++) {
                Preference preference = mRoot.getPreference(i);
                if (preference instanceof EditTextPreference) {
                    String key = preference.getKey();
                    String value = ((EditTextPreference) preference).getText();
                    if (TextUtils.isEmpty(value)) {
                        jsonObject.add(key,null);
                        continue;
                    }
                    if (value.contains("[")&&value.contains("]")) {
                        value = value.replace("[","").replace("]","").replace("\"","");
                        String arrs[] = value.split(",");
                        JsonArray array = new JsonArray();
                        for (String a : arrs) {
                            array.add(a);
                        }
                        jsonObject.add(key,array);
                    } else {
                        jsonObject.addProperty(key,value);
                    }
                }
            }
            System.out.println(jsonObject.toString());
            if (isBluetooth) {
                BluetoothManager.INSTANCE.sendConfig(mIp,mName,jsonObject.toString());
            } else if (isRemote) {
                SocketIoInstance.INSTANCE.getClient().sendConfig(mName,jsonObject.toString());
            }
            else {
                ClientManager.getManager().getClient(mIp).sendConfig(mName,jsonObject.toString());
            }
        } else if (id == R.id.add) {
            EditText editText = new EditText(getActivity());
            new AlertDialog.Builder(getActivity())
                    .setTitle("输入新增字段名")
                    .setView(editText)
                    .setNegativeButton("取消",null)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EditTextPreference preference = new EditTextPreference(getContext());
                            String key = editText.getText().toString();
                            if (TextUtils.isEmpty(key)) {
                                return;
                            }
                            preference.setTitle(key);
                            preference.setKey(key);
                            preference.setPersistent(false);
                            preference.setIconSpaceReserved(false);
                            preference.setSummaryProvider(EditTextPreference.SimpleSummaryProvider.getInstance());
                            mRoot.addPreference(preference);
                        }
                    }).show();
        }
        return super.onOptionsItemSelected(item);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SendStatus status) {
        if (status.cmd == IOHelper.CMD_SET_CONFIG) {
            if ( status.status == 0) {
                Activity activity = getActivity();
                if (activity != null) {
                    Toast.makeText(activity,"设置成功",Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity,"设置失败 " + status.status,Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
